package com.yh.web;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yh.pojo.Permission;
import com.yh.pojo.Role;
import com.yh.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author by 张晨光
 * @date 2023/11/7 15:29
 */
@Controller
@RequestMapping("role")
public class RoleController {
    @Autowired
    RoleService roleService;

    /**
     * 复习：ModelAndView
     * @param page
     * @param size
     * @return
     */
    @GetMapping("findAll")
    public ModelAndView findAll(@RequestParam(value = "page",defaultValue = "1") Integer page,
                                @RequestParam(value = "size",defaultValue = "5") Integer size){
        ModelAndView mv=new ModelAndView(); //模型视图对象;
        PageHelper.startPage(page,size);
        List<Role> roleList = roleService.findAllRoles();
        PageInfo<Role>pageInfo=new PageInfo<>(roleList);
        //模型视图对象，如何办？
        mv.addObject("pageInfo",pageInfo);      //数据;
        mv.setViewName("role-list");
        return mv;
    }
    /**
     * 新增用户功能
     */
    @PostMapping("save")
    public String save(Role role){
        roleService.addRole(role);
        return "redirect:findAll";
    }
    @GetMapping("findById")
    public String findById(Integer id, Model model){
        Role role = roleService.findById(id);
        model.addAttribute("role",role);
        return "role-show";
    }

    /**
     * 去可以添加资源的页面，给角色; 去这里--》role-permission-add.html
     * 修改数据的提交.
     * @param id
     * @param model
     * @return
     */
    @GetMapping("findRoleByIdAndAllPermission")
   public String findRoleByIdAndAllPermission(Integer id,Model model){
        Role role = roleService.findById(id);
        model.addAttribute("role",role);        //可以设置${role.id}
        List<Permission> permissionList = roleService.findOtherPermission(id);
        model.addAttribute("permissionList",permissionList);
        return "role-permission-add";
    }

    @PostMapping("addPermissionToRole")
    public String addPermissionToRole(@RequestParam("roleId")Integer roleId,
                                      @RequestParam("ids")Integer[]ids){
            roleService.addPermissionToRole(roleId,ids);
            return "redirect:findAll";
    }

    @GetMapping("deleteRole")
    public String deleteRole(Integer id){
        roleService.deleteRoleByRoleId(id);
        return "redirect:findAll";
    }
}
